package io.fft.flight.common.utils.flightHttp;

import io.fft.flight.common.utils.SpringContextUtils;
import io.fft.flight.common.utils.flightHttp.reponse.BaseResVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;

/**
 * @Author: likailun
 * @Description:
 * @Date: create in 2024/4/28 23:33
 */
@Slf4j
public class MyHttpUtil {

    private static RestTemplate restTemplate;
    private static SupplierProp supplierProp;
    static {
        restTemplate= SpringContextUtils.getBean(RestTemplate.class);
        supplierProp= SpringContextUtils.getBean(SupplierProp.class);
    }
    public static <T> BaseResVO<T> post(String url, FlightReqEntity<? extends ReqData> entity) {
        entity.setCompanyCode(supplierProp.getCompanyCode());
        entity.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
        entity.setSign(md5(supplierProp.getCompanyCode(),supplierProp.getYzlSecret(),entity.getTimeStamp()));
        final BaseResVO<T> baseResVO = restTemplate.postForObject(supplierProp.getUrl() + url, entity, BaseResVO.class);
        log.info("请求结果：{}", baseResVO.toString());
        return baseResVO;
    }

    private static String md5(String companyCode,String secret,String timeStamp) {
        StringBuffer sb = new StringBuffer(32);
        try {
            MessageDigest md   = MessageDigest.getInstance("MD5");
            byte[] array      = md.digest((companyCode+secret+timeStamp).getBytes("utf-8"));
            for (int i = 0; i < array.length; i++) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
            }
        } catch (Exception e) {
            return null;
        }
        return sb.toString();
    }
}
